package com.itboye.jinpuyiyuan.app;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.multidex.MultiDex;
import android.support.v4.app.ActivityCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.alibaba.mobileim.IYWP2PPushListener;
import com.alibaba.mobileim.IYWTribePushListener;
import com.alibaba.mobileim.YWAPI;
import com.alibaba.mobileim.YWIMKit;
import com.alibaba.mobileim.aop.AdviceBinder;
import com.alibaba.mobileim.aop.PointCutEnum;
import com.alibaba.mobileim.channel.constant.B2BConstant;
import com.alibaba.mobileim.channel.util.AccountUtils;
import com.alibaba.mobileim.channel.util.WxLog;
import com.alibaba.mobileim.contact.IYWContact;
import com.alibaba.mobileim.contact.IYWContactCacheUpdateListener;
import com.alibaba.mobileim.contact.IYWContactOperateNotifyListener;
import com.alibaba.mobileim.conversation.IYWConversationService;
import com.alibaba.mobileim.conversation.YWConversation;
import com.alibaba.mobileim.conversation.YWCustomMessageBody;
import com.alibaba.mobileim.conversation.YWMessage;
import com.alibaba.mobileim.fundamental.model.YWIMSmiley;
import com.alibaba.mobileim.gingko.model.tribe.YWTribe;
import com.alibaba.mobileim.ui.chat.widget.YWSmilyMgr;
import com.alibaba.mobileim.utility.IMAutoLoginInfoStoreUtil;
import com.alibaba.mobileim.utility.IMNotificationUtils;
import com.alibaba.tcms.env.EnvManager;
import com.alibaba.tcms.env.TcmsEnvType;
import com.alibaba.tcms.env.YWEnvManager;
import com.alibaba.tcms.env.YWEnvType;
import com.alibaba.wxlib.util.SysUtil;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.itboye.jinpuyiyuan.MainActivity;
import com.itboye.jinpuyiyuan.R;
import com.itboye.jinpuyiyuan.activity.login.LoginOrRegisterActivity;
import com.itboye.jinpuyiyuan.activity.me.SetUpActivity;
import com.itboye.jinpuyiyuan.utils.IMKit.CustomSampleHelper;
import com.itboye.jinpuyiyuan.utils.IMKit.LoginSampleHelper;
import com.itboye.jinpuyiyuan.utils.logincontroller.LoginController;
import com.itboye.jinpuyiyuan.utils.logincontroller.UnLoginState;
import com.itboye.jinpuyiyuan.utils.sputil.Const;
import com.itboye.jinpuyiyuan.utils.sputil.SPUtils;
import com.itboye.jinpuyiyuan.widget.FilterUtil;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.cookie.store.PersistentCookieStore;
import com.lzy.okhttputils.model.HttpParams;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import static com.itboye.jinpuyiyuan.utils.IMKit.LoginSampleHelper.APP_KEY_TEST;

/**
 * Created by admin on 2017/1/13.
 */
public class MyApplication extends Application {
    private List<WeakReference<Activity>> activityList = new LinkedList<>();
    public static MyApplication instatnce;
    private static RequestQueue queue;
    public static String toUid;
    //读写权限
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private YWIMKit mIMKit;
    public static YWEnvType sEnvType = YWEnvType.TEST;
    public PushAgent mPushAgent;
    public  IWXAPI api;
    public PushAgent getmPushAgent() {
        return mPushAgent;
    }

    public static MyApplication getInstance() {

        return instatnce;

    }

    //微信介入
    private  void  regToWx(){
        api= WXAPIFactory.createWXAPI(this,Const.APP_ID_WX,true);
        api.registerApp(Const.APP_ID_WX);
    }

    //初始化openIM
    public void initWXSDK() {
//必须首先执行这部分代码, 如果在":TCMSSevice"进程中，无需进行云旺（OpenIM）和app业务的初始化，以节省内存;
        SysUtil.setApplication(this);
        if (SysUtil.isTCMSServiceProcess(this)) {
            return;
        }
//第一个参数是Application Context
//这里的Const.OPEN_APPKEY即应用创建时申请的APP_KEY，同时初始化必须是在主进程中
        if (SysUtil.isMainProcess()) {
            YWAPI.init(instatnce, Const.OPEN_APPKEY);
        }


    }

    @Override
    public void onCreate() {
        super.onCreate();
        instatnce = this;

        queue = Volley.newRequestQueue(this);

        //必须调用初始化
        HttpParams params = new HttpParams();
        OkHttpUtils.init(this);
        //以下都不是必须的，根据需要自行选择
        OkHttpUtils.getInstance()//
                .debug("OkHttpUtils")                                              //是否打开调试
                .setConnectTimeout(OkHttpUtils.DEFAULT_MILLISECONDS)               //全局的连接超时时间
                .setReadTimeOut(OkHttpUtils.DEFAULT_MILLISECONDS)                  //全局的读取超时时间
                .setWriteTimeOut(OkHttpUtils.DEFAULT_MILLISECONDS)                 //全局的写入超时时间
                //                .setCookieStore(new MemoryCookieStore())                           //cookie使用内存缓存（app退出后，cookie消失）
                .setCookieStore(new PersistentCookieStore())                       //cookie持久化存储，如果cookie不过期，则一直有效
                //                .addCommonHeaders(headers)                                         //设置全局公共头
                .addCommonParams(params);                                          //设置全局公共参数
//        initPushSDK();
        initUMengPush();
        initWXSDK();
        //初始化云旺SDK
        initYWSDK();
        //注册到微信
        regToWx();
    }


    @Override
    protected void attachBaseContext(Context base) {
             super.attachBaseContext(base);
             MultiDex.install(this) ;
          }

    private void initYWSDK() {
        SysUtil.setApplication(this);
        //todo 只在主进程进行云旺SDK的初始化!!!
        if(SysUtil.isMainProcess()){
            //TODO 注意：--------------------------------------
            //  以下步骤调用顺序有严格要求，请按照示例的步骤（todo step）
            // 的顺序调用！
            //TODO --------------------------------------------

            // ------[todo step1]-------------
            //［IM定制初始化］，如果不需要定制化，可以去掉此方法的调用
            //todo 注意：由于增加全局初始化，该配置需最先执行！

            CustomSampleHelper.initCustom();

            // ------[todo step2]-------------
            //SDK初始化
            LoginSampleHelper.getInstance().initSDK_Sample(this);

            //后期将使用Override的方式进行集中配置，请参照YWSDKGlobalConfigSample
            YWAPI.enableSDKLogOutput(true);
//            LeakCanary.install(this);
        }
    }


    public void addActivity(Activity activity) {

        activityList.add(new WeakReference<Activity>(activity));
    }

    public void removeAllActivity(){
//        FilterUtil.putClearSharePre(this);

//        SPUtils.put(this,null,Const.LOGIN_PASSWORD,"");
            for (WeakReference<Activity> list :activityList){
                Activity activity = list.get();
                if (activity!=null){
                    activity.finish();
                }

            }


    }
    /**
     * @return the queue
     */
    public static RequestQueue getQueue() {
        return queue;
    }

    //
    public static <T> void addRequest(Request<T> request) {
        request.addMarker("itboye");
        getQueue().add(request);
    }

    private void initUMengPush() {
        mPushAgent = PushAgent.getInstance(this);
        mPushAgent.getPushIntentServiceClass();
        mPushAgent.setDebugMode(true);
        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            /**
             * 自定义消息的回调方法
             * */
            @Override
            public void dealWithCustomMessage(final Context context,
                                              final UMessage msg) {
                new Handler().post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        // 对自定义消息的处理方式，点击或者忽略
                        boolean isClickOrDismissed = true;
                        if (isClickOrDismissed) {
                            // 自定义消息的点击统计
                            UTrack.getInstance(getApplicationContext())
                                    .trackMsgClick(msg);
                        } else {
                            // 自定义消息的忽略统计
                            UTrack.getInstance(getApplicationContext())
                                    .trackMsgDismissed(msg);
                        }
                        Toast.makeText(context, msg.custom, Toast.LENGTH_LONG)
                                .show();
                    }
                });
            }

            @Override
            public void dealWithNotificationMessage(Context arg0, UMessage arg1) {
                // TODO Auto-generated method stub
                super.dealWithNotificationMessage(arg0, arg1);
                Log.d("umessage==",arg1+"");
            }

//            /**
//             * 自定义通知栏样式的回调方法
//             * */
//            @SuppressLint("NewApi")
//            @Override
//            public Notification getNotification(Context context, UMessage msg) {
//                switch (msg.builder_id) {
//                    case 1:
//                        Notification.Builder builder = new Notification.Builder(
//                                context);
//                        RemoteViews myNotificationView = new RemoteViews(
//                                context.getPackageName(),
//                                R.layout.notification_view);
//                        myNotificationView.setTextViewText(R.id.notification_title,
//                                msg.title);
//                        myNotificationView.setTextViewText(R.id.notification_text,
//                                msg.text);
//                        myNotificationView.setImageViewBitmap(
//                                R.id.notification_large_icon,
//                                getLargeIcon(context, msg));
//                        myNotificationView.setImageViewResource(
//                                R.id.notification_small_icon,
//                                getSmallIconId(context, msg));
//                        builder.setContent(myNotificationView)
//                                .setSmallIcon(getSmallIconId(context, msg))
//                                .setTicker(msg.ticker).setAutoCancel(true);
//
//                        return builder.getNotification();
//                    default:
//                        // 默认为0，若填写的builder_id并不存在，也使用默认。
//                        return super.getNotification(context, msg);
//                }
//            }
        };
        mPushAgent.setMessageHandler(messageHandler);

        /**
         * 自定义行为的回调处理 UmengNotificationClickHandler是在BroadcastReceiver中被调用，故
         * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
         * */
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {

            }

            @Override
            public void openActivity(Context arg0, UMessage arg1) {
                // TODO Auto-generated method stub
                // super.openActivity(arg0, arg1);//必须注释掉才能执行指定类的跳转
//                Gson gson = new Gson();
//                NotificationBean bean = gson.fromJson(arg1.getRaw().toString(),
//                        NotificationBean.class);
//                Intent intent = new Intent();
//                String uid = SPUtils.get(ctx, null, SPContants.USER_ID, "")
//                        + "";
//                if (uid.equals("")) {
//                    intent = new Intent(ctx, LoginActivity.class);
//                    startActivity(intent);
//                    return;
//                }
//                if (bean.getBody().getActivity().equals("system_message")) {
//                    intent = new Intent(ctx, ActivitySystemMessage.class);
//                    intent.putExtra("type", 1);
//                } else if (bean.getBody().getActivity()
//                        .equals("contract_message")) {
//                    intent = new Intent(ctx, ActivityMySign.class);
//                    intent.putExtra("contract_no", bean.getExtra().getId());
//                    Intent intent1 = new Intent(OrderFragment.REFRESH);
//                    sendBroadcast(intent1);
//                } else if (bean.getBody().getActivity().equals("lock_message")) {
//                    intent = new Intent(ctx, ActivitySystemMessage.class);
//                    intent.putExtra("type", 4);
//                } else if (bean.getBody().getActivity().equals("wallet_message")) {
//                    intent = new Intent(ctx, ActivityMyWallte.class);
//                    intent.putExtra("type", 5);
//                } else if (bean.getBody().getActivity().equals("rent_message")) {
//                    //intent = new Intent(ctx, WodeFangyuanActivity.class);
//                    intent = new Intent(ctx, ActivityXuanZuKe.class);
//                    intent.putExtra("house_no", bean.getExtra().getHouse_no());
//                }
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                startActivity(intent);
            }
        };
        // 使用自定义的NotificationHandler，来结合友盟统计处理消息通知
        // 参考http://bbs.umeng.com/thread-11112-1-1.html
        // CustomNotificationHandler notificationClickHandler = new
        // CustomNotificationHandler();
        mPushAgent.setNotificationClickHandler(notificationClickHandler);

        // 注册推送服务 每次调用register都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                System.out.println(">>>deviceToken" + deviceToken);
                SPUtils.put(MyApplication.instatnce,null,Const.UMENG_DEVICE,deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                System.out.println(">>>deviceToken--onFailure" + s + "s1"+s1);

            }
        });
    }

//    public void initPushSDK(){
//        mPushAgent = PushAgent.getInstance(this);
//        // 注册推送服务 每次调用register都会回调该接口
//        mPushAgent.register(new IUmengRegisterCallback() {
//            @Override
//            public void onSuccess(String deviceToken) {
//                System.out.println(">>>deviceToken" + deviceToken);
//            }
//
//            @Override
//            public void onFailure(String s, String s1) {
//                System.out.println(">>>deviceToken--onFailure" + s + "s1"+s1);
//
//            }
//        });
//    }

    public void initDevice(){
        //会话列表UI相关
//        AdviceBinder.bindAdvice(PointCutEnum.CONVERSATION_FRAGMENT_UI_POINTCUT, ConversationListUICustomSample.class);
//        //会话列表业务相关
//        AdviceBinder.bindAdvice(PointCutEnum.CONVERSATION_FRAGMENT_OPERATION_POINTCUT, ConversationListOperationCustomSample.class);

    }



}
